package com.zoro.barn.commons.webcommons.response.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * print response log
 * @author zhaoxingwu
 */
public class ResponseLogAdvice implements ResponseBodyAdvice<Object> {

    public ResponseLogAdvice() {
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        try {
            String uri = request.getURI().getRawPath();
            Logger thisLogger = LoggerFactory.getLogger(uri);
            if (thisLogger.isInfoEnabled()) {
                thisLogger.info("RESPONSE  :  uri {}, method {}, contentType {}, response {}", uri, request.getMethod(),
                        request.getHeaders().getContentType(), body.toString());
            }
        } catch (Exception e) {
            logger.error("error occurred when log response, error message:" + e.getMessage());
        }
        return body;
    }
}
